package com.skyable.common.utils;

import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
import java.util.Map;

/**
 * @author GaoYuan
 * @date 2020/12/10 15:19
 * @desc 接入层接口调用代理类
 */
public class SaApiUtil {
	public final static String HTTP_METHOD_GET = "GET";
	public final static String HTTP_METHOD_POST = "POST";
	public final static String HEADER_CONTENT_TYPE = "Content-Type";
	public final static String HEADER_MAJOR_DOMAMIN_ID = "X-Zc-Major-Domain-Id";
	public final static String HEADER_SUB_DOMAMIN_ID = "X-Zc-Sub-Domain-Id";
	public final static String HEADER_VERSION = "X-Zc-Version";
	public final static String HEADER_TRACE_ID = "X-Zc-Trace-Id";
	public final static String HEADER_DEVELOPER_ID = "X-Zc-Developer-Id";

	public final static String HEADER_CONTENT_TYPE_X_ZC_OBJECT = "application/x-zc-object";
	public final static String HEADER_CONTENT_TYPE_JSON = "application/json";
	public final static String HEADER_CONTENT_TYPE_OCTET_STREAM = "application/octet-stream";

	private static String ERROR_CODE_STR = "errorCode";
	private static String HEADER_MSG_ATTR_ERROR_CODE = "X-Zc-Msg-Attr_errorCode";

	public static String doPost(String url, Map<String, Object> headerMap, String queryBody) {

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {

			URL realUrl = new URL(url);

			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			if (headerMap != null) {
				for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue() + "");
				}

			}
			connection.setRequestMethod("POST");
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			out = new PrintWriter(connection.getOutputStream());
			out.write(queryBody);
			out.flush();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;

	}


	public static String doPost(String url, Map<String, Object> headerMap, byte[] payload) {
		//返回信息
		JSONObject serviceResult = new JSONObject();
		OutputStream outputStream = null;
		InputStream inputStream = null;
		try {
			URL realUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			// 设置通用的请求属性
			if (headerMap != null) {
				for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
					connection.setRequestProperty(entry.getKey(), entry.getValue() + "");
				}
			}
			connection.setRequestMethod(SaApiUtil.HTTP_METHOD_POST);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			outputStream = connection.getOutputStream();
			outputStream.write(payload);
			inputStream = connection.getInputStream();
			String respContentType = connection.getHeaderFields().get("Content-Type").get(0);
			Integer errorCode = -1;
			String error = "";
			Boolean requestError = false;
			//判断是否返回错误信息
			if (respContentType.equals(HEADER_CONTENT_TYPE_X_ZC_OBJECT)) {
				// body 里面取 错误信息
				BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				StringBuilder result = new StringBuilder();
				String line = "";
				while ((line = in.readLine()) != null) {
					result.append(line);
				}
				JSONObject resultObj = JSONObject.parseObject(result.toString());
				if (resultObj.containsKey(ERROR_CODE_STR)) {
					errorCode = resultObj.getInteger("errorCode");
					error = resultObj.getString("error");
					requestError = true;
				}
			} else {
				// header 里面取错误信息
				if (connection.getHeaderFields().get(HEADER_MSG_ATTR_ERROR_CODE) != null) {
					errorCode = Integer.parseInt(connection.getHeaderFields().get("X-Zc-Msg-Attr_errorCode").get(0));
					error = connection.getHeaderFields().get("X-Zc-Msg-Attr_error").get(0);
					requestError = true;
				}
			}
			// 有错误
			if (requestError) {
				serviceResult.put("errorCode",errorCode);
				serviceResult.put("error",error);
				return serviceResult.toJSONString();
			}
			// 没错误
			String result = "";
			String contentLength = connection.getHeaderFields().get("Content-Length").get(0);
			if(connection.getHeaderFields().containsKey("X-Zc-Msg-Attr_code")) {
				String msgCode = connection.getHeaderFields().get("X-Zc-Msg-Attr_code").get(0);
				serviceResult.put("msgCode", msgCode);
			}

			byte[] bytes = new byte[Integer.parseInt(contentLength)];
			inputStream.read(bytes);
			result = Base64.getEncoder().encodeToString(bytes);

			serviceResult.put("deviceResponse", result);

		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}

		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (outputStream != null) {
					outputStream.close();
				}
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return serviceResult.toJSONString();
	}
}
